﻿using System;
using System.Collections.Generic;
using System.Data.Odbc;
using System.Linq;
using System.Web;

namespace HitachiService.DBAccess
{
    public class SchedulePolicyAccess : DataAccess
    {
        public static SchedulePolicyData GetSchedulePolicyByProjectId(int project_id)
        {
            String sql =
                "select " +
                "gid,project_id,common_mask " +
                "from t_schedule_policy where project_id=" + project_id + ";";
            OdbcConnection conn = GetConnection();
            OdbcCommand cmd = new OdbcCommand(sql, conn);

            conn.Open();
            OdbcDataReader reader = cmd.ExecuteReader();
            SchedulePolicyData policy = null;
            while (reader.Read())
            {
                policy = new SchedulePolicyData();
                policy.ProjectId = project_id;
                policy.ID = ReadInt(reader["gid"]);
                policy.Mask = ReadInt(reader["common_mask"]);
                break;
            }
            conn.Close();
            return policy;
        }

        public static int SaveSchedulePolicy(SchedulePolicyData data)
        {
            int last_insert_id = 1;
            String sql =
                "insert into t_schedule_policy " +
                "(project_id,common_mask) values (" +
                data.ProjectId + "," + data.Mask +
                ");";
            if (data.ID != 0)
            {
                last_insert_id = 0;
                sql =
                "update t_schedule_policy set " +
                "common_mask=" + data.Mask +
                " where gid=" + data.ID;
            }
            OdbcConnection conn = GetConnection();
            OdbcCommand cmd = new OdbcCommand(sql, conn);
            conn.Open();
            OdbcDataReader reader = cmd.ExecuteReader();
            if (last_insert_id > 0)
            {
                sql = "select @@IDENTITY;";
                OdbcCommand cmd_last = new OdbcCommand(sql, conn);
                last_insert_id = Convert.ToInt32(cmd_last.ExecuteScalar());
                data.ID = last_insert_id;
            }
            conn.Close();
            return data.ID;
        }
    }
}